<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // ["a", "banana", "app", "appl", "ap", "apply", "apple"]
        var longestWord = function (words) {
            words.sort();
            let set = new Set();
            res = '';
            for (let item of words) {
                if (item.length == 1 || set.has(item.substring(0, item.length - 1))) {
                    // 预防长度一定时， 后面的'apply' 会覆盖前面的 'apple'
                    res = item.length > res.length ? item : res;
                    set.add(item);
                }
            }
            return res
        };
        console.log(longestWord(["a", "banana", "app", "appl", "ap", "apply", "apple"]));
    </script>
</body>

</html>